<template>
  <view class="min-h-screen bg-[#f5f5f5]">
    <!-- 页面头部 -->
    <PageHeader title="评价用户" :showBack="true" :onlyBack="false" />

    <!-- 用户信息卡片 -->
    <view class="mx-[32rpx] mt-[24rpx] bg-white rounded-[20rpx] p-[32rpx] shadow-md evaluate-card">
      <view class="flex items-center">
        <image
          :src="userInfo.avatar_url || 'http://www.dzgktf.com/templets/default/images/wtyt.jpg'"
          class="w-[88rpx] h-[88rpx] rounded-full mr-[28rpx] border-2 border-gray-100 user-avatar"
          mode="aspectFill"
        />
        <view class="flex-1">
          <text class="text-[32rpx] font-semibold text-[#1a1a1a] block mb-[12rpx] leading-[1.4]">{{ userInfo.name }}</text>
          <text class="text-[28rpx] text-[#666] leading-[1.5] truncate">{{ userInfo.taskTitle }}</text>
        </view>
      </view>
    </view>

    <!-- 评价表单 -->
    <view class="mx-[32rpx] mt-[24rpx] bg-white rounded-[20rpx] p-[32rpx] shadow-md evaluate-card">
      <!-- 星级评分 -->
      <view class="mb-[48rpx]">
        <text class="text-[32rpx] font-semibold text-[#1a1a1a] mb-[32rpx] block leading-[1.4]">服务评分</text>
        <view class="flex items-center justify-center gap-x-[32rpx]">
          <view
            v-for="star in 5"
            :key="star"
            class="w-[72rpx] h-[72rpx] flex items-center justify-center cursor-pointer transition-all duration-300 hover:scale-110 active:scale-95 star-container"
            @click="handleStarClick(star)"
          >
            <IconFont
              :name="star <= rating ? 'star-fill' : 'star'"
              :class="star <= rating ? 'text-yellow-500' : 'text-gray-200'"
              size="30"
            />
          </view>
        </view>
        <view class="text-center mt-[24rpx]">
          <text class="text-[30rpx] text-[#666] font-medium leading-[1.5]">{{ getRatingText() }}</text>
        </view>
      </view>

      <!-- 评论输入 -->
      <view class="mb-[48rpx]">
        <text class="text-[32rpx] font-semibold text-[#1a1a1a] mb-[24rpx] block box-border leading-[1.4]">评价内容</text>
        <nut-textarea
          v-model="comment"
          class="w-full min-h-[180rpx] box-border p-[24rpx] border-2 border-gray-200 rounded-[16rpx] text-[30rpx] text-[#333] leading-[1.6]"
          placeholder="请输入您的评价内容..."
          maxlength="200"
          auto-size
          :auto-size="{ minRows: 4, maxRows: 8 }"
        />
        <view class="flex justify-end mt-[20rpx]">
          <text class="text-[26rpx] text-gray-400 leading-[1.4]">{{ getFinalCommentLength() }}/200</text>
        </view>
      </view>

      <!-- 快捷评价标签 -->
      <view class="mb-[48rpx]">
        <text class="text-[32rpx] font-semibold text-[#1a1a1a] mb-[24rpx] block leading-[1.4]">快捷评价</text>
        <view class="flex flex-wrap gap-[24rpx]">
          <view
            v-for="tag in quickTags"
            :key="tag"
            class="px-[18rpx] py-[10rpx] rounded-[20rpx] text-[20rpx] cursor-pointer transition-all duration-300 font-medium leading-[1.4] quick-tag"
            :class="[
              commentIncludesTag(tag) ? 'bg-blue-500 text-white shadow-md' : 'bg-gray-50 text-gray-700 hover:bg-gray-100'
            ]"
            @click="toggleTag(tag)"
          >
            {{ tag }}
          </view>
        </view>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="fixed flex-center bottom-0 left-0 right-0 bg-white p-[32rpx] shadow-lg border-t border-gray-100">
      <nut-button
        type="primary"
        class="w-full"
        :disabled="!canSubmit"
        :loading="isSubmitting"
        @click="handleSubmit"
      >
        提交评价
      </nut-button>
    </view>

    <!-- 底部安全区域 -->
    <view class="h-[140rpx]"></view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { IconFont } from '@nutui/icons-vue-taro';
// import { Button as nutButton, Textarea as nutTextarea } from '@nutui/nutui-taro';
import { getFullPath, post } from '@/utils/request';
import Taro from '@tarojs/taro';

/**
 * 评价页面
 * @description 用于评价任务执行者，包含星级评分、评论输入、快捷标签等功能
 */

// 用户信息
const userInfo = ref({
  name: '',
  avatar: '',
  taskTitle: '',
  rid: ''//报名id
});

// 评分
const rating = ref(0);

// 评论内容
const comment = ref('');

// 快捷评价标签
const quickTags = ref([
  '工作认真',
  '态度良好',
  '按时完成',
  '沟通顺畅',
  '专业能力强',
  '服务周到',
  '响应及时',
  '质量优秀'
]);

// 提交状态
const isSubmitting = ref(false);

// 是否可以提交
const canSubmit = computed(() => {
  return rating.value > 0 && comment.value.trim().length > 0;
});

/**
 * 页面加载时获取参数
 */
onMounted(() => {
  const params = Taro.getCurrentInstance().router?.params || {};
  userInfo.value = {
    name: decodeURIComponent(params.userName || '用户'),
    avatar: getFullPath(decodeURIComponent(params.userAvatar)),
    taskTitle: decodeURIComponent(params.taskName || '任务'),
    rid: params.taskId || ''
  };

  userInfo.value.userId = params.userId || '';
  //调用 /my/otherPeople 接口
  post("/my/otherPeople", {
    id: params.userId
  }).then((res) => {
    console.log("用户信息:", res);
    userInfo.value = res.data.columns;
  });
  
  console.log('评价页面参数:', params);
  console.log('用户信息:', userInfo.value);
});

/**
 * 检查评论中是否包含指定标签
 */
const commentIncludesTag = (tag) => {
  const commentTrim = comment.value.trim();
  if (!commentTrim) return false;
  return commentTrim.split('，').includes(tag);
};

/**
 * 点击星级
 */
const handleStarClick = (star) => {
  rating.value = star;
  
  // 添加点击反馈动画
  const starElements = document.querySelectorAll('.star-container');
  if (starElements[star - 1]) {
    starElements[star - 1].classList.add('success-animation');
    setTimeout(() => {
      starElements[star - 1].classList.remove('success-animation');
    }, 600);
  }
  
  // 显示评分反馈
  // Taro.showToast({
  //   title: getRatingText(),
  //   icon: 'none',
  //   duration: 1000
  // });
};

/**
 * 获取评分文字
 */
const getRatingText = () => {
  const texts = ['', '很差', '较差', '一般', '良好', '优秀'];
  return texts[rating.value] || '请选择评分';
};

/**
 * 获取最终评论长度
 */
const getFinalCommentLength = () => {
  return comment.value.trim().length;
};

/**
 * 切换标签选择
 */
const toggleTag = (tag) => {
  const commentTrim = comment.value.trim();
  const commentArr = commentTrim ? commentTrim.split('，') : [];

  if (commentArr.includes(tag)) {
    // 已包含标签，移除
    comment.value = commentArr.filter(item => item !== tag).join('，');
  } else {
    // 未包含标签，添加
    commentArr.push(tag);
    comment.value = commentArr.join('，');
  }
  
  // 添加标签切换反馈
  const tagElement = event?.target?.closest('.quick-tag');
  if (tagElement) {
    tagElement.classList.add('success-animation');
    setTimeout(() => {
      tagElement.classList.remove('success-animation');
    }, 600);
  }
};

/**
 * 提交评价
 */
const handleSubmit = async () => {
  if (!canSubmit.value) return;

  try {
    isSubmitting.value = true;
    
    const params = Taro.getCurrentInstance().router?.params || {};
    const taskId = params.taskId;
    const isDay = params.day == 1;
    let scoreUrl = isDay ? "/recruitmentDaily/score" : "/task/score";
    let updateSignUpUrl = isDay ? "/recruitmentDaily/updateSignUp" : "/task/updateStage";
    if(params.type == 3){
      scoreUrl = "/check/score";
      updateSignUpUrl = "/check/updateSignUp";
    }

    
    // 调用评价接口
    const res = await post(scoreUrl, {
      id: taskId,
      score: rating.value,
      reviewContent: comment.value,
      tags: comment.value.split('，').filter(tag => quickTags.value.includes(tag))
    });

    if (res.code === 0) {
      Taro.showToast({ 
        title: '评价提交成功', 
        icon: 'success',
        duration: 2000
      });

      const res = await post(updateSignUpUrl, {
        id: params.taskId,
        status: 27,
      });

      
      // 延迟返回上一页
      setTimeout(() => {
        navigateBack();
      }, 1500);
    } else {
      Taro.showToast({ 
        title: res.message || '评价提交失败', 
        icon: 'error' 
      });
    }
  } catch (error) {
    console.error('评价提交失败:', error);
    Taro.showToast({ 
      title: '网络错误，请重试', 
      icon: 'error' 
    });
  } finally {
    isSubmitting.value = false;
  }
};

/**
 * 返回上一页
 */
const navigateBack = () => {
  Taro.navigateBack();
};
</script>

<style lang="scss">
.nut-textarea {
  background-color: #fafafa;
  border: 2rpx solid #e5e5e5;
  transition: all 0.3s ease;

  &:focus {
    border-color: #165DFF;
    box-shadow: 0 0 0 6rpx rgba(22, 93, 255, 0.08);
    background-color: #ffffff;
  }
}

// 按钮样式优化
.nut-button {
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }
  
  &:disabled {
    opacity: 0.6;
    transform: none;
  }
}

// 星级评分样式优化
.star-container {
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background: radial-gradient(circle, rgba(255, 193, 7, 0.1) 0%, transparent 70%);
    opacity: 0;
    transition: opacity 0.3s ease;
  }
  
  &:hover::after {
    opacity: 1;
  }
}

// 快捷标签样式优化
.quick-tag {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &:hover {
    transform: translateY(-2rpx);
  }
  
  &.active {
    box-shadow: 0 4rpx 12rpx rgba(22, 93, 255, 0.3);
  }
}

// 卡片悬停效果
.evaluate-card {
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
  }
}

// 头像样式优化
.user-avatar {
  transition: all 0.3s ease;
  
  &:hover {
    transform: scale(1.05);
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
  }
}

// 响应式字体大小
@media (max-width: 375px) {
  .text-responsive {
    font-size: 28rpx;
  }
}

// 加载状态优化
.loading-state {
  opacity: 0.7;
  pointer-events: none;
}

// 成功状态动画
@keyframes successPulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.success-animation {
  animation: successPulse 0.6s ease-in-out;
}

// 输入框聚焦动画
@keyframes focusGlow {
  0% { box-shadow: 0 0 0 0 rgba(22, 93, 255, 0.4); }
  70% { box-shadow: 0 0 0 6rpx rgba(22, 93, 255, 0); }
  100% { box-shadow: 0 0 0 0 rgba(22, 93, 255, 0); }
}

.focus-glow {
  animation: focusGlow 0.6s ease-out;
}
</style>
